'use strict';


const Package = require('@xqc-ink-cli/package')
const log = require('@xqc-ink-cli/log')
const { execCommand } = require('@xqc-ink-cli/utils')

const path = require('path')

const SETTINGS = {
    init: "@xqc-ink-cli/init"
    // init: "@imooc-cli/init"
}

const CACHE_DIR = 'dependencies/'
// 1. targetPath -> modulePath
// 2. modulePath -> Package(npm模块)
// 3. Package.getRootFilePath(获取入口文件)
// 4. Package.update / Package.install
async function execRoot() {
    
    let pkg;
    let storeDir = ''
    let targetPath = process.env.CLI_TARGET_PATH
    const homePath = process.env.CLI_HOME_PATH
    log.verbose('targetPath', targetPath); 
    log.verbose('homePath', homePath);

    const command = arguments[arguments.length - 1]
    const commandName = command.name() // init
    const packageName = SETTINGS[commandName]
    const packageVersion = 'latest'

    // targetPath 可能来源于本地、缓存、下载
    if(!targetPath){
        targetPath = path.resolve(homePath, CACHE_DIR)
        storeDir = path.resolve(targetPath, 'node_modules')
        console.log('storeDir : ', storeDir);
        pkg = new Package({
            targetPath,
            storeDir: storeDir,
            packageName: packageName,
            packageVersion: packageVersion,
        })
        console.log('storeDir2 : ', pkg);
        /**
         * 4. Package.install / Package.update
         * Package 是否存在
         * Y:更新 Package
         * N:安装 Package
         * E:获取本地代码入口文(获取package的入口文件)
        */
        await pkg.exists() ? await pkg.update() : await pkg.install()
    }
    else{
         pkg = new Package({
            targetPath,
            packageName: packageName,
            packageVersion: packageVersion,
        })
    }
  
    const rootFile = await pkg.getRootFilePath()
    log.verbose('rootFile', rootFile)
    if(rootFile){
        try { 
            // 在当前进程中使用(通过传入targetPath)
            // require(rootFile).call(null, Array.from(arguments))

            // 在node子进程中调用
            const args = Array.from(arguments)
            args[args.length - 1] = prepare(args[args.length - 1])
            const code = `require('${rootFile}').call(null, ${JSON.stringify(args)})`
            const child = execCommand('node', ['-e', code], {
                cwd: process.cwd(),
                stdio: 'inherit'
            })
            child.on('error', (e) =>{
                log.error(e.message)
                process.exit(1)
            })
            child.on('exit', e => {
                log.verbose('命令执行成功: ' + e)
            })
        } 
        catch (error) {
            log.error(error)
        }
    } 
}

 

function prepare(cmd){
    const o = Object.create(null)
    const opt = cmd._optionValues 
    for (const key in opt) {
        o[key] =  opt[key]
    }
    Object.keys(cmd).forEach(key => {
        if(cmd.hasOwnProperty(key) && key !== 'parent' && !key.startsWith('_')){
            o[key] = cmd[key]
        }
    })  
    return o
}

module.exports = execRoot;  